यूटिल मॉड्यूल क्या है?
यूटिल मॉड्यूल एक कोर नोड.जेएस मॉड्यूल है जो सामान्य कार्यों के लिए उपयोगिता कार्यों का एक सेट प्रदान करता है।
यह Node.js डेवलपर्स के लिए स्विस आर्मी चाकू की तरह है, जो निम्न जैसे समाधान पेश करता है:
सामान्य उपयोग के मामले
प्लेसहोल्डर्स के साथ स्ट्रिंग्स को फ़ॉर्मेट करना
स्ट्रिंग स्वरूपण और प्रतिस्थापन
डिबगिंग के लिए वस्तुओं की जांच करना
सामग्री विश्लेषण और प्रतिनिधित्व
कॉलबैक और वादों के बीच स्विच करना
अतुल्यकालिक कोड स्विचिंग
परीक्षण और सत्यापन टाइप करें
डेटा प्रकार सत्यापन
छोड़े गए अलर्ट को संभालना
एपीआई परित्याग प्रबंधन
डिबगिंग और लॉगिंग
डिबगिंग और लॉगिंग तकनीक
महत्वपूर्ण लाभ
नोट:
यूटिल मॉड्यूल में कुछ फ़ंक्शन Node.js के आंतरिक उपयोग के लिए हैं, लेकिन कई Node.js एप्लिकेशन बनाने वाले डेवलपर्स के लिए मूल्यवान उपकरण हैं।
मॉड्यूल को Node.js के साथ बंडल किया गया है, इसलिए किसी इंस्टॉलेशन की आवश्यकता नहीं है।
यूटिल के साथ शुरुआत करना
यहां एक पूर्वाभ्यास उदाहरण दिया गया है जो यूटिल मॉड्यूल से क्रियाशील कई उपयोगिताओं को प्रदर्शित करता है:
मूल अनुप्रयोग उदाहरण
const util = require('util');
const fs = require('fs');
// Convert callback-based fs.readFile to Promise-based
const readFile = util.promisify(fs.readFile);
// Format strings with placeholders
const greeting = util.format('Hello, %s! Today is %s', 'Developer', new Date().toDateString());
console.log(greeting);
// Inspect an object with custom options
const obj = {
name: 'Test',
nested: { a: 1, b: [2, 3] },
fn: function() { return 'test'; }
};
console.log(util.inspect(obj, { colors: true, depth: 2 }));
// Use debug logging
const debug = util.debuglog('app');
debug('This will only show if NODE_DEBUG=app');
// Example of using promisify with async/await
async function readConfig() {
try {
const data = await readFile('package.json', 'utf8');
console.log('Package name:', JSON.parse(data).name);
} catch (err) {
console.error('Error reading config:', err);
}
}
readConfig();
आयात करना और स्थापित करना
आप अपने मॉड्यूल सेटअप और आवश्यकताओं के आधार पर यूटिल मॉड्यूल को कई तरीकों से आयात कर सकते हैं:
कॉमनजेएस (नोड.जेएस डिफ़ॉल्ट)
// Import the entire module
const util = require('util');
// Import specific functions using destructuring
const { promisify, inspect, format } = require('util');
// Using strict mode (recommended)
const assert = require('assert').strict;
// For TypeScript users
// import * as util from 'util';
// import { promisify, inspect } from 'util';
ES Modules (Node.js 12+)
// Default import
import util from 'util';
// Named imports
import { promisify, inspect } from 'util';
// Rename imports
import { promisify as pify } from 'util';
// Dynamic import (Node.js 14+)
const { promisify } = await import('util');
// Using with TypeScript types
// import * as util from 'util';
// import type { InspectOptions } from 'util';
सर्वश्रेष्ठ प्रणालियां:
बेहतर ट्री-शेकिंग और छोटे बंडलों के लिए, केवल उन कार्यों के लिए आयात को नष्ट करना पसंद करें जिनकी आपको आवश्यकता है।
यूटिल मॉड्यूल काफी बड़ा है, और आप आमतौर पर इसकी कार्यक्षमता का केवल एक छोटा उपसमूह ही उपयोग करते हैं।
स्ट्रिंग डिजाइन और निरीक्षण
यूटिल मॉड्यूल स्ट्रिंग्स को फ़ॉर्मेट करने और ऑब्जेक्ट का निरीक्षण करने के लिए शक्तिशाली उपकरण प्रदान करता है, जो लॉगिंग और डिबगिंग के लिए विशेष रूप से उपयोगी होते हैं।
util.format(format[, ...args])
प्रिंटफ जैसे प्रारूप स्ट्रिंग के रूप में पहले तर्क का उपयोग करके एक स्वरूपित स्ट्रिंग लौटाता है।
यह कंसोल.लॉग() के समान है, लेकिन इसे प्रिंट करने के बजाय एक स्वरूपित स्ट्रिंग लौटाता है।
प्रारूप विनिर्देशक:
| उल्लेख | व्याख्या |
|---|---|
| %s | डोरी |
| %d | संख्या (पूर्णांक और फ़्लोट दोनों) |
| %i | पूर्णांक संख्या |
| %f | फ़्लोटिंग पॉइंट मान |
| %j | JSON (यदि तर्क में गोलाकार उद्धरण हैं तो '[परिपत्र]' से प्रतिस्थापित) |
| %o | विषय (विषय की जांच करें) |
| %O | विषय (पूरे विवरण के साथ विषय की जांच करें) |
| %% | एकल प्रतिशत चिह्न ('%') |
const util = require('util');
// Basic formatting
const formatted = util.format('Hello, %s!', 'World');
console.log(formatted); // 'Hello, World!'
// Multiple placeholders
const multiFormatted = util.format(
'My name is %s. I am %d years old and I love %s.',
'Kai',
30,
'Node.js'
);
console.log(multiFormatted);
// 'My name is Kai. I am 30 years old and I love Node.js.'
// Available specifiers
const specifiers = util.format(
'String: %s, Number: %d, JSON: %j, Character: %c',
'hello',
42,
{ name: 'Object' },
65 // ASCII code for 'A'
);
console.log(specifiers);
// Extra arguments are concatenated with spaces
const extra = util.format('Hello', 'World', 'from', 'Node.js');
console.log(extra); // 'Hello World from Node.js'
util.inspect(object[, options])
डिबगिंग के लिए उपयोगी किसी ऑब्जेक्ट का स्ट्रिंग प्रतिनिधित्व लौटाता है।
Node.js ऑब्जेक्ट को कंसोल पर प्रिंट करने के लिए आंतरिक रूप से इसका उपयोग करता है।
सामान्य उपयोग के मामले:
- जटिल वस्तुओं को डिबग करना
- मानव-स्पर्श योग्य वस्तु अभ्यावेदन बनाना
- वस्तुओं को वृत्ताकार उद्धरण चिह्नों के साथ पंजीकृत करना
- रिकॉर्ड्स में ऑब्जेक्ट डिस्प्ले को कस्टमाइज़ करना
सामान्य विकल्प:
| विकल्प | व्याख्या | गलती करना |
|---|---|---|
| showHidden | अनगिनत गुण दिखाएं | false |
| depth | दोहराने के लिए चरणों की संख्या | 2, null for unlimited |
| colors | एएनएसआई रंग कोड जोड़ें | false |
| customInspect | कस्टम निरीक्षण कार्यों का उपयोग करें | true |
| showProxy | प्रॉक्सी विवरण दिखाएँ | false |
| maxArrayLength | जोड़ने के लिए सरणी तत्वों की अधिकतम संख्या | 100 |
| breakLength | वह लंबाई जिस पर भौतिक ताकतों को तोड़ना होगा | 60 |
| compact | नई पंक्तियों पर विशेषताएँ तोड़ें | true for arrays, false for objects |
| sorted | गुण क्रमबद्ध करें | false, true for alphabetical, function for custom sort |
const util = require('util');
// Basic usage
const obj = {
name: 'John',
age: 30,
hobbies: ['reading', 'coding'],
address: {
city: 'New York',
country: 'USA'
},
toString() {
return `${this.name}, ${this.age}`;
}
};
// Default inspection
console.log(util.inspect(obj));
// Custom options
console.log(util.inspect(obj, {
colors: true, // Add ANSI color codes
depth: 0, // Only inspect the first level
showHidden: true, // Show non-enumerable properties
compact: false, // Don't format objects on a single line
showProxy: true, // Show proxy details
maxArrayLength: 3, // Limit array elements displayed
breakLength: 50, // Line break after 50 characters
sorted: true // Sort object properties alphabetically
}));
// Circular references
const circular = { name: 'Circular' };
circular.self = circular;
console.log(util.inspect(circular));
util.inspect.custom
ऑब्जेक्ट विश्लेषण को अनुकूलित करने के लिए उपयोग किया जाने वाला प्रतीक।
यह वस्तुओं को पार्स किए जाने पर अपने स्वयं के स्ट्रिंग प्रतिनिधित्व को परिभाषित करने की अनुमति देता है।
सर्वोत्तम प्रथाएं:
const util = require('util');
// Class with custom inspection
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
this._private = 'hidden information';
}
// Custom inspect method
[util.inspect.custom](depth, options) {
return `Person(${this.name}, ${this.age})`;
}
}
const kai = new Person('Kai', 30);
// Custom inspection is used
console.log(util.inspect(kai)); // Person(Kai, 30)
// Directly using console.log also uses custom inspection
console.log(kai); // Person(Kai, 30)
वादे और Async अनुप्रयोग
Node.js Util , callback- Promise- API .
util.promisify(original)
Node.js callback callback- Promise .
यह पुराने Node.js API के साथ काम करने के लिए उपयोगी है जो कॉलबैक का उपयोग करते हैं।
util.promisify :
- पुराने Node.js API के साथ काम करना जो कॉलबैक का उपयोग करते हैं
- प्रॉमिस का उपयोग करने के लिए कॉलबैक-आधारित लाइब्रेरी बदलना
- कॉलबैक हटाकर एसिंक/प्रतीक्षा कोड को सरल बनाना
- Node.js callback (error-first, single result)
सीमाएँ:
- Node.js callback : (err, value) => {}
- उन फ़ंक्शंस के साथ काम नहीं करता जो कॉलबैक में एकाधिक मान लौटाते हैं
- अधिक जटिल एपीआई के लिए कस्टम प्रॉमिसिफिकेशन की आवश्यकता हो सकती है
const util = require('util');
const fs = require('fs');
// Convert fs.readFile from callback-based to Promise-based
const readFilePromise = util.promisify(fs.readFile);
// Now we can use it with async/await or Promise chaining
async function readFileExample() {
try {
// Using the promisified function
const data = await readFilePromise('package.json', 'utf8');
console.log('File content:', data.substring(0, 100) + '...');
// Error handling with try/catch
return 'File read successfully';
} catch (err) {
console.error('Error reading file:', err.message);
return 'Error reading file';
}
}
readFileExample().then(result => {
console.log('Result:', result);
});
util.callbackify(original)
एक फ़ंक्शन को परिवर्तित करता है जो एक प्रॉमिस लौटाता है जो एक फ़ंक्शन में परिवर्तित होता है जो Node.js कॉलबैक विधि को आमंत्रित करता है।
यह कॉलबैक-आधारित एपीआई के साथ काम करने के लिए उपयोगी है जो कॉलबैक फ़ंक्शन की अपेक्षा करता है।
util.callbackify :
- कॉलबैक-आधारित एपीआई के साथ वादा-आधारित कोड को एकीकृत करना
- पुस्तकालयों में पश्चगामी अनुकूलता बनाए रखना
- Node.js- callbacks API
- कॉलबैक से वादों की ओर चरणबद्ध माइग्रेशन
सर्वोत्तम प्रथाएं:
const util = require('util');
// A Promise-based function
async function fetchUserData(id) {
if (!id) {
throw new Error('ID is required');
}
// Simulate API request
return {
id,
name: `User ${id}`,
email: `user${id}@example.com`
};
}
// Convert to callback-based
const fetchUserDataCallback = util.callbackify(fetchUserData);
// Using the callback-based function
fetchUserDataCallback(1, (err, user) => {
if (err) {
console.error('Error:', err);
return;
}
console.log('User data:', user);
});
// Error handling
fetchUserDataCallback(null, (err, user) => {
if (err) {
console.error('Error occurred:', err.message);
return;
}
console.log('User data:', user); // This won't execute
});
util.promisify.custom
वादा व्यवहार को अनुकूलित करने के लिए प्रतीक। जब किसी फ़ंक्शन का वादा किया जाता है तो यह आपको एक कस्टम कार्यान्वयन प्रदान करने की अनुमति देता है।
कस्टम वादे के लिए मामलों का उपयोग करें:
- ऐसे फ़ंक्शन जो स्थिर कॉलबैक विधि का पालन नहीं करते हैं
- एपीआई जो कॉलबैक में एकाधिक मान लौटाते हैं
- कस्टम त्रुटि प्रबंधन या परिणामों का रूपांतरण
- विशिष्ट उपयोग के मामलों के लिए प्रदर्शन का अनुकूलन
- वचनबद्धता के दौरान अतिरिक्त कार्यक्षमता जोड़ना
const util = require('util');
// Function with custom promisification
function doSomething(options, callback) {
callback(null, 'regular result');
}
// Define custom promisification
doSomething[util.promisify.custom] = (options) => {
return Promise.resolve('custom promisified result');
};
// Use the custom promisification
const promisified = util.promisify(doSomething);
// Compare the results
async function compareResults() {
// Original function with callback
doSomething({}, (err, result) => {
console.log('Callback result:', result);
});
// Custom promisified function
const customResult = await promisified({});
console.log('Promisified result:', customResult);
}
compareResults();
परीक्षण एप्लिकेशन टाइप करें
यूटिल मॉड्यूल जावास्क्रिप्ट के टाइपोफ़ ऑपरेटर की तुलना में अधिक विश्वसनीय प्रकार-परीक्षण उपयोगिताएँ प्रदान करता है, विशेष रूप से अंतर्निहित ऑब्जेक्ट और Node.js-विशिष्ट प्रकारों के लिए।
util.types का उपयोग क्यों किया जाना चाहिए?
const util = require('util');
// Example values
const values = [
'string',
123,
true,
Symbol('symbol'),
{ key: 'value' },
[1, 2, 3],
null,
undefined,
() => {},
BigInt(123),
new Date(),
/regex/,
Buffer.from('buffer'),
new Error('error')
];
// Check types for each value
values.forEach(value => {
console.log(`Value: ${util.inspect(value)}`);
console.log(`- isArray: ${util.types.isArrayBuffer(value)}`);
console.log(`- isDate: ${util.types.isDate(value)}`);
console.log(`- isRegExp: ${util.types.isRegExp(value)}`);
console.log(`- isNativeError: ${util.types.isNativeError(value)}`);
console.log(`- isPromise: ${util.types.isPromise(value)}`);
console.log(`- isPrimitive: ${util.isPrimitive(value)}`);
console.log(`- isString: ${util.isString(value)}`);
console.log(`- isNumber: ${util.isNumber(value)}`);
console.log(`- isBoolean: ${util.isBoolean(value)}`);
console.log(`- isSymbol: ${util.types.isSymbol(value)}`);
console.log(`- isNull: ${value === null}`);
console.log(`- isUndefined: ${value === undefined}`);
console.log(`- isFunction: ${util.types.isFunction(value)}`);
console.log(`- isBuffer: ${Buffer.isBuffer(value)}`);
console.log('---');
});
नोट:
util में कई टाइप-चेकिंग फ़ंक्शंस को Array.isArray() के पक्ष में हटा दिया गया है, जैसे कि util.types या जावास्क्रिप्ट की अंतर्निहित प्रकार की जाँच विधियाँ।
util.types
util.types JavaScript Node.js- :
const util = require('util');
// JavaScript built-in types
console.log('util.types.isDate(new Date()):',
util.types.isDate(new Date()));
console.log('util.types.isRegExp(/test/):',
util.types.isRegExp(/test/));
console.log('util.types.isPromise(Promise.resolve()):',
util.types.isPromise(Promise.resolve()));
// Node.js-specific types
console.log('util.types.isArrayBuffer(new ArrayBuffer(0)):',
util.types.isArrayBuffer(new ArrayBuffer(0)));
console.log('util.types.isSharedArrayBuffer(new SharedArrayBuffer(0)):',
util.types.isSharedArrayBuffer(new SharedArrayBuffer(0)));
console.log('util.types.isUint8Array(new Uint8Array()):',
util.types.isUint8Array(new Uint8Array()));
// More advanced types
console.log('util.types.isProxy(new Proxy({}, {})):',
util.types.isProxy(new Proxy({}, {})));
console.log('util.types.isExternal(Requiring C++ binding):',
'Not demonstrated in this example');
परित्याग आवेदन
Node.js API .
परित्याग रणनीति:
util.deprecate(fn, msg[, code])
इंगित करता है कि एक फ़ंक्शन निरस्त कर दिया गया है और कॉल करने पर एक चेतावनी देता है।
const util = require('util');
// Original function
function oldFunction(x, y) {
return x + y;
}
// Deprecate the function
const deprecatedFunction = util.deprecate(
oldFunction,
'oldFunction() is deprecated. Use newFunction() instead.',
'DEP0001'
);
// New function
function newFunction(x, y) {
return x + y;
}
// Using the deprecated function will show a warning
console.log('Result:', deprecatedFunction(5, 10));
// Using the new function
console.log('Result:', newFunction(5, 10));
ड्रॉपआउट अलर्ट प्रबंधित करें
आप पर्यावरण चर का उपयोग करके ड्रॉपआउट चेतावनियों के प्रदर्शन को नियंत्रित कर सकते हैं:
# Show all deprecation warnings
NODE_OPTIONS='--trace-deprecation'
# Show only the first occurrence of each deprecation
NODE_OPTIONS='--no-deprecation'
# Silence all deprecation warnings
NODE_OPTIONS='--no-warnings'
# Turn deprecation warnings into exceptions
NODE_OPTIONS='--throw-deprecation'
डिबगिंग और विकास अनुप्रयोग
Node.js , .
util.debuglog(section)
एक फ़ंक्शन बनाता है जो NODE_DEBUG पर्यावरण चर के आधार पर stderr को सशर्त रूप से डिबग संदेश लिखता है।
यह पूर्ण विशेषताओं वाली रिकॉर्डिंग लाइब्रेरी के लिए एक हल्का प्रतिस्थापन है।
डिबग लॉगिंग के लिए सर्वोत्तम अभ्यास:
उदाहरण उपयोग:
// Enable debug logging for specific modules
// NODE_DEBUG=app,db node your-app.js
// In your application
const debugApp = util.debuglog('app');
const debugDB = util.debuglog('db');
// These will only log when 'app' is in NODE_DEBUG
debugApp('Application started with config: %j', config);
// These will only log when 'db' is in NODE_DEBUG
debugDB('Connected to database: %s', connectionString);
// Enable all debug logs (not recommended in production)
// NODE_DEBUG=* node your-app.js
const util = require('util');
// Create debug loggers for different sections
const debugApp = util.debuglog('app');
const debugDB = util.debuglog('db');
const debugAuth = util.debuglog('auth');
// These messages only appear when NODE_DEBUG includes 'app'
debugApp('Application starting...');
debugApp('Configuration loaded from %j', { source: 'config.json' });
// These messages only appear when NODE_DEBUG includes 'db'
debugDB('Connected to database');
debugDB('Query executed: %s', 'SELECT * FROM users');
// These messages only appear when NODE_DEBUG includes 'auth'
debugAuth('User authenticated: %s', 'john.doe');
// To see these messages, run your app with:
// NODE_DEBUG=app,db node your-app.js
console.log('Application running normally (this always shows)');
सारांश
Node.js Util Node.js :
स्ट्रिंग स्वरूपण
util.format()
सामग्री विश्लेषण
util.inspect()
एसिंक परिवर्तन
util.promisify() util.callbackify()
टाइप करने की परीक्षा
util.types
परित्याग प्रबंधन
util.deprecate()
लॉग को डीबग करें
util.debuglog()
इन उपयोगिताओं को समझकर और उपयोग करके, आप अत्यधिक रखरखाव योग्य, डिबग करने योग्य और प्रदर्शन करने योग्य Node.js एप्लिकेशन लिख सकते हैं।